package org.demo.jpa.controller;

import java.util.List;

import org.demo.jpa.common.Result;
import org.demo.jpa.dao.IUserDao;
import org.demo.jpa.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value="/user")
public class JpaController {
	@Autowired 
	private IUserDao userDao;

	@RequestMapping(value="/list", method = RequestMethod.GET)
	public List<User> getUsers(){
		return userDao.findAll();
	}

	@RequestMapping(value="/{id}", method=RequestMethod.GET)
	public User getUserById(@PathVariable("id") long id){
		return userDao.findOne(id);
	}
	
	@RequestMapping(value="/{id}", method=RequestMethod.PUT)
	public Result updateUser(@PathVariable("id") long id, 
			@RequestParam(value="name", required=true)String name, 
			@RequestParam(value="age", required=true)int age) {
		User user = new User(); 
		user.setName(name);
		user.setAge(age);
		user.setId(id);
		User newUser = userDao.saveAndFlush(user); 
		if(newUser != null) {
			return Result.success().setData(1); 
		}else {
			return Result.fail(); 
		}
	}
	
	@RequestMapping(value="", method=RequestMethod.POST)
	public Result createUser(@RequestParam(value="name") String name, 
			@RequestParam(value="age") int age) {
		User user = new User(); 
		user.setName(name);
		user.setAge(age);
		User newUser = userDao.save(user); 
		if(newUser != null) {
			return Result.success().setData(1); 
		}else {
			return Result.fail(); 
		}
	}
	
	@RequestMapping(value="/{id}", method=RequestMethod.DELETE)
	public Result deleteUser(@PathVariable("id")long id) {
		userDao.delete(id);
		return Result.success().setData(1);
	}

}
